using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using Musicman.Business;
using MusicmanWeb.Custom;
using Musicman.Common.Entities;
using System.IO;

namespace MusicmanWeb
{

    public partial class FilesOverview : MusicmanPage
    {
        protected override void Page_Load(object sender, EventArgs e)
        {
            ReddirectNonActiveSession();
            if (!IsPostBack)
            {
                List<SearchJob> jobs = SearchJobManager.Instance.LoadAllSearchJobs();
                JobsDDL.DataSource = jobs;
                JobsDDL.DataBind();

                JobsGV.DataSource = jobs;
                JobsGV.DataBind();
            }
        }

        protected void AddToDownloads_Command(object sender, CommandEventArgs e)
        {
            long userID = Int64.Parse(User.Identity.Name);
            
            List<long> fileIds = new List<long>();
            foreach (int index in SearchGV.GetSelectedIndices())
            {
                long key = (long)SearchGV.DataKeys[index].Value;
                // can't add files that are only temporaly cached to pending downloads
                if (key > 0)
                {
                    fileIds.Add(key);
                }
            }
            SearchFileManager.Instance.AddToPendingDonwloads(userID, fileIds);
            List<SearchFile> files = Cache["searchresult"] as List<SearchFile>;
            SearchGV.DataSource = files;
            SearchGV.DataBind();
        }

        protected void BtnSearch_Click(object sender, CommandEventArgs e)
        {
            long fileID = 0;
            Int64.TryParse(e.CommandArgument.ToString(), out fileID);
            // when random refresh collecion or search within same folder
            if (e.CommandName == "random" || (e.CommandName == "samefolder" && fileID > 0))
            {
                Cache.Remove("searchresult");
            }
            List<SearchFile> files = null; 
            if (fileID <= 0)
            {
                files = GetSearchFiles(e.CommandName);
            }
            else
            {
                files = GetSearchFiles(e.CommandName, Int64.Parse(e.CommandArgument.ToString()));
            }
            SearchGV.DataSource = files;
            SearchGV.DataBind();

            // add to downloads button
            if (files != null && files.Count != 0)
            {
                UpdateButton.Visible = true;
            }
            else
            {
                UpdateButton.Visible = false;
            }
        }

        private List<SearchFile> GetSearchFiles(string searchType)
        {
            return GetSearchFiles(searchType, long.MaxValue);
        }

        private List<SearchFile> GetSearchFiles(string searchType, long searchFileID)
        {
            if (Cache["searchtype"] == null || (string)Cache["searchtype"] != searchType)
            {
                Cache["searchtype"] = searchType;
            }
            if (Cache["keyword"] == null || (string)Cache["keyword"] != txtKeyword.Text)
            {
                Cache["keyword"] = txtKeyword.Text;
            }
            if (Cache["jobid"] == null || (string)Cache["jobid"] != JobsDDL.SelectedValue)
            {
                Cache["jobid"] = JobsDDL.SelectedValue;
            }
            if (Cache["count"] == null || (string)Cache["count"] != txtCount.Text)
            {
                Cache["count"] = txtCount.Text;
            }
            if (Cache["minsize"] == null || (string)Cache["minsize"] != txtMinSize.Text)
            {
                Cache["minsize"] = txtMinSize.Text;
            } 

            List<SearchFile> files = null;
            if (Cache["searchresult"] == null)
            {
                long start = DateTime.Now.Ticks;

                int top = 0;
                long minSize = 0;
                long jobId = 0;
                Int32.TryParse(txtCount.Text, out top);
                Int64.TryParse(JobsDDL.SelectedValue, out jobId);
                Int64.TryParse(txtMinSize.Text, out minSize);
                minSize = minSize * Int64.Parse(this.measureunit.Value);
                if (searchType == "search")
                {
                    files = SearchFileManager.Instance.LoadSearchFiles(jobId, txtKeyword.Text, top, minSize);
                }
                else if (searchType == "topdownloads")
                {
                    files = SearchFileManager.Instance.LoadTopDownwloadesFiles(jobId, txtKeyword.Text, top, minSize);
                }
                else if (searchType == "toprated")
                {
                    files = SearchFileManager.Instance.LoadTopRatedFiles(jobId, txtKeyword.Text, top, minSize);
                }
                else if (searchType == "latest")
                {
                    files = SearchFileManager.Instance.LoadLatestFiles(jobId, txtKeyword.Text, top, minSize);
                }
                else if (searchType == "random")
                {
                    files = SearchFileManager.Instance.LoadRandomFiles(jobId, txtKeyword.Text, top == 0 ? 50 : top, minSize);
                }
                else if (searchType == "samefolder")
                {
                    files = new List<SearchFile>();
                    SearchFile sf = SearchFileManager.Instance.GetSearchFile(searchFileID);
                    if (sf != null)
                    {
                        DirectoryInfo di = new DirectoryInfo(sf.FilePath);
                        if (di.Exists)
                        {
                            FileInfo[] fInfos = di.GetFiles("*.*", SearchOption.AllDirectories);
                            for (int i = 0; i < fInfos.Length; i++)
                            {
                                if (fInfos[i].Exists)
                                {
                                    SearchFile file = new SearchFile(fInfos[i], jobId);
                                    file.SearchFileID = -1 - i;
                                    files.Add(file);
                                }
                            }
                        }
                    }
                }
                long end = DateTime.Now.Ticks;
                Cache.Insert("searchresult", files,
                    new System.Web.Caching.CacheDependency(new string[] { }, new string[] { "keyword", "jobid", "count", "minsize", "searchtype"}),
                    System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 10, 0));
                
                this.statusLbl.Text = String.Format("{0} files found in {1}", files.Count, new TimeSpan(end - start));
            }
            else
            {
                files = Cache["searchresult"] as List<SearchFile>;
            }
            return files;
        }

        protected void SearchGV_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            SearchFile sf = e.Row.DataItem as SearchFile;
            if (sf != null)
            {
                if (sf.PresentSequence > 0)
                {
                    e.Row.CssClass = "oldfiles";
                }
                else if (sf.PresentSequence == -1)
                {
                    e.Row.CssClass = "newfiles";
                }
                e.Row.Cells[0].Text = Musicman.Common.Utilities.Converter.NameTrimmed(sf.FilePath + "\\" + sf.Name, 30);
                e.Row.Cells[0].ToolTip = sf.FilePath + "\\" + sf.Name;
                e.Row.Cells[1].Text = Musicman.Common.Utilities.Converter.NameTrimmed(sf.Name, 40);
                e.Row.Cells[1].ToolTip = sf.Name;
                e.Row.Cells[2].Text = Musicman.Common.Utilities.Converter.LengthMB(sf.Length);
            }
        }

        protected void JobsGV_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            SearchJob sj = e.Row.DataItem as SearchJob;
            if (sj != null)
            {
                e.Row.Cells[1].Text = Musicman.Common.Utilities.Converter.NameTrimmed(sj.AllCriteria, 15);
                e.Row.Cells[1].ToolTip = sj.AllCriteria;
                e.Row.Cells[5].Text = Musicman.Common.Utilities.Converter.LengthGB(sj.TotalLength);
            }
        }

        protected void SearchGV_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            MyGridView gv = sender as MyGridView;
            List<SearchFile> files = GetSearchFiles(Cache["searchtype"] as string);
            gv.DataSource = files;
            gv.PageIndex = e.NewPageIndex;
            gv.DataBind();
        }

        protected void SearchGV_Sorting(object sender, GridViewSortEventArgs e)
        {
            MyGridView gv = sender as MyGridView;
            List<SearchFile> files = GetSearchFiles(Cache["searchtype"] as string);
            SortDirection sortDirection = e.SortDirection;
            if (ViewState[e.SortExpression] != null)
            {
                sortDirection = (SortDirection)ViewState[e.SortExpression] == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending;
            }
            ViewState[e.SortExpression] = sortDirection;

            if (e.SortExpression == "Length")
            {
                files.Sort(delegate(SearchFile sf1, SearchFile sf2)
                {
                    return sortDirection == SortDirection.Ascending ?
                         sf1.Length.CompareTo(sf2.Length) :
                         sf2.Length.CompareTo(sf1.Length);
                });
            }
            else if (e.SortExpression == "Name")
            {
                files.Sort(delegate(SearchFile sf1, SearchFile sf2)
                {
                    return sortDirection == SortDirection.Ascending ?
                         sf1.Name.CompareTo(sf2.Name) :
                         sf2.Name.CompareTo(sf1.Name);
                });
            }
            else if (e.SortExpression == "Location")
            {
                files.Sort(delegate(SearchFile sf1, SearchFile sf2)
                {
                    return sortDirection == SortDirection.Ascending ?
                         sf1.FilePath.CompareTo(sf2.FilePath) :
                         sf2.FilePath.CompareTo(sf1.FilePath);
                });
            }
            gv.DataSource = files;
            gv.DataBind();
        }
    }
}
